/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.klikmee.sms.core.base.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContexts;
import javax.persistence.PersistenceException;
import javax.persistence.PersistenceUnit;

import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author makcro
 */
@Transactional
public abstract class AbstractDAO<T> {

	@PersistenceContext
	protected EntityManager	entityManager;

	private Class<T>		entityClass;

	public AbstractDAO( Class<T> entityClass ) {
		this.entityClass = entityClass;
	}

	@Transactional
	public void create( T entity ) {
		this.entityManager.persist( entity );
	}

	@Transactional
	public void edit( T entity ) {
		this.entityManager.merge( entity );
	}

	@Transactional
	public void remove( T entity ) {
		T entityForDeletiing = this.entityManager.merge( entity );
		this.entityManager.remove( entityForDeletiing );
	}

	public T find( Object id ) {
		return this.entityManager.find( entityClass, id );
	}

	public T refresh( T entity ) {
		T merged = this.entityManager.merge( entity );
		this.entityManager.refresh( merged );
		return merged;
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		javax.persistence.criteria.CriteriaQuery cq = this.entityManager.getCriteriaBuilder().createQuery();
		cq.select( cq.from( entityClass ) );
		return this.entityManager.createQuery( cq ).getResultList();
	}
}
